package com.cjl.eater.interceptor;

import com.cjl.eater.pojos.Eater;
import com.cjl.utils.common.JwtUtil;
import com.cjl.utils.thread.EaterThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author cjl
 * @version v1.0
 * @description TODO
 * @createTime 2023/2/16 13:55
 */
@Slf4j
@Component
public class EaterFirstInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //请求头中获取食客id
        String eaterId = request.getHeader("eaterId");

        //判断eaterId是否存在
        if (eaterId == null) return false;

        try {
            //将eaterId封装到threadLocal中
            Eater eater = Eater.builder()
                    .id(Integer.parseInt(eaterId))
                    .build();
            EaterThreadUtil.set(eater);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return false;
        }
        log.info("添加eaterId到EaterThreadUtil中。。。");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        EaterThreadUtil.remove();
    }
}
